package com.xxxy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxy.entity.Credentials;
import com.xxxy.mapper.CredentialsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;

import java.util.Collections;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private CredentialsMapper credentialsMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Credentials> queryWrapper = new QueryWrapper<>();//创建查询条件
        queryWrapper.eq("name",username);//设置查询条件

        Credentials credentials = credentialsMapper.selectOne(queryWrapper);//查询用户
        if (credentials == null){
            String errorMsg="user:"+username+ "not found";
            System.out.println(errorMsg);
            throw new UsernameNotFoundException(errorMsg);
        }

        List<GrantedAuthority> authorities = Collections.singletonList((GrantedAuthority)  ()-> "USER");//添加权限

        return new User(credentials.getName(),credentials.getPassword(),authorities);//创建用户
    }
}
